package com.xy.blog.user.dao.impl;

import com.github.pagehelper.PageHelper;
import com.xy.blog.core.dao.IBaseCommonDao;
import com.xy.blog.core.id.SnowflakeIdWorker;
import com.xy.blog.core.springmvc.result.page.PageReq;
import com.xy.blog.core.springmvc.result.page.PageResp;
import com.xy.blog.user.controller.model.req.query.AccountQuery;
import com.xy.blog.user.dao.IAccountDao;
import com.xy.blog.user.dao.mapper.AccountMapper;
import com.xy.blog.user.dao.model.AccountDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description:
 * @date 2020/3/4
 */
@Repository
public class AccountDaoImpl implements IAccountDao , IBaseCommonDao<AccountDO, AccountQuery> {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public PageResp<AccountDO> listByPage(PageReq<AccountQuery> req) {
        PageHelper.startPage(req);
        List<AccountDO> accountDOS = accountMapper.selectAll();
        return PageResp.data(accountDOS);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void save(AccountDO item) {
        if (item.getId() == null) {
            item.setId(SnowflakeIdWorker.generateId());
        }

        if (item.getCreateTime() == null) {
            item.setCreateTime(LocalDateTime.now());
        }
        if (item.getUpdateTime() == null) {
            item.setUpdateTime(LocalDateTime.now());
        }
        if (item.getLock() == null) {
            item.setLock("false");
        }
        accountMapper.insertSelective(item);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateById(AccountDO item) {
        accountMapper.updateByPrimaryKeySelective(item);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void deleteById(Long id) {
        accountMapper.deleteByPrimaryKey(id);
    }

    @Override
    public AccountDO getById(Long id) {
        return accountMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<AccountDO> select(AccountDO item) {
        return accountMapper.select(item);
    }

    @Override
    public int selectCount(AccountDO item) {
        return accountMapper.selectCount(item);
    }

    @Override
    public AccountDO getByAccount(String account) {
        AccountDO accountDO = new AccountDO();
        accountDO.setAccount(account);
        return accountMapper.selectOne(accountDO);
    }
}
